﻿using Sgr.Domain.Entities;
using Sgr.Domain.Entities.Auditing;
using Sgr.Exceptions;

namespace Sgr.UPMS.Domain.Organizations
{
    /// <summary>
    /// 组织邀请链接
    /// </summary>
    public class OrganizationInvitation : CreationAndModifyAuditedEntity<long, long>, IAggregateRoot, IOptimisticLock
    {
        /// <summary>
        /// 组织ID
        /// </summary>
        public long OrganizationId { get; private set; }

        /// <summary>
        /// 邀请码
        /// </summary>
        public string InvitationCode { get; private set; } = string.Empty;

        /// <summary>
        /// 邀请链接过期时间
        /// </summary>
        public DateTime ExpireTime { get; private set; }

        /// <summary>
        /// 可使用次数（-1表示不限制）
        /// </summary>
        public int UsageLimit { get; private set; }

        /// <summary>
        /// 已使用次数
        /// </summary>
        public int UsedCount { get; private set; }

        /// <summary>
        /// 描述
        /// </summary>
        public string? Description { get; private set; }

        /// <summary>
        /// 链接状态
        /// </summary>
        public EntityStates State { get; private set; }

        protected OrganizationInvitation()
        { }

        internal OrganizationInvitation(
            long organizationId,
            string invitationCode,
            DateTime expireTime,
            int usageLimit = -1,
            string? description = null)
        {
            OrganizationId = organizationId;
            InvitationCode = invitationCode;
            ExpireTime = expireTime;
            UsageLimit = usageLimit;
            Description = description;
            UsedCount = 0;
            State = EntityStates.Normal;
        }

        /// <summary>
        /// 检查邀请链接是否可用
        /// </summary>
        public bool IsValid()
        {
            if (State != EntityStates.Normal)
                return false;

            if (DateTime.UtcNow > ExpireTime)
                return false;

            if (UsageLimit != -1 && UsedCount >= UsageLimit)
                return false;

            return true;
        }

        /// <summary>
        /// 使用邀请链接
        /// </summary>
        public void Use()
        {
            if (!IsValid())
                throw DomainException.LimitExceededError("邀请链接已失效");

            UsedCount++;
        }

        /// <summary>
        /// 禁用邀请链接
        /// </summary>
        public void Disable()
        {
            State = EntityStates.Deactivate;
        }

        #region IOptimisticLock (乐观锁)

        /// <summary>
        /// 行版本
        /// </summary>
        public long RowVersion { get; set; }

        #endregion IOptimisticLock (乐观锁)
    }
}